<template>
  <div class="owner-detail">
    <section class="header">
      <a-page-header
          class="demo-page-header"
          style="border: 1px solid rgb(235, 237, 240)"
          :class="notBack ? 'hide-back' : ''"
          :title="detail.name"
          @back="goBack(false)"
      >
        <template #backIcon>
          <cu-icon
              type="org-zukeguanli"
              v-if="isModal"
              style="font-size: 24px"
          />
          <ArrowLeftOutlined v-else/>
        </template>
        <template #extra>
          <a-space :style="isModal ? 'padding-right: 50px' : ''">
            <a-button v-permission="['ownerList', 'curd', 'delete']" @click.stop="OwnerDelete(text)"> 删除</a-button>
            <a-button v-permission="['ownerList', 'curd', 'edit']" type="primary" @click.stop="OwnerEdit(text)">
              编辑
            </a-button>
          </a-space>
        </template>

        <template #footer>
          <a-tabs v-model:activeKey="activeTabKey" size="small">
            <!-- <a-tab-pane key="detail" tab="详情" />
            <a-tab-pane key="contract" tab="合同" />
            <a-tab-pane key="bill" tab="账单" /> -->
            <a-tab-pane
                v-for="(item, key) in tabList"
                :key="key"
                :tab="item.title"
            />
          </a-tabs>
        </template>
      </a-page-header>
    </section>
    <section class="content">
      <div v-show="activeTabKey == 'detail'">
        <a-row :gutter="[12, 12]">
          <a-col :span="24">
            <a-card title="基本信息" :bordered="false">
              <a-descriptions layout="vertical" :column="4" :colon="false">
                <a-descriptions-item label="联系人">{{
                    detail.contact_name || "--"
                  }}
                </a-descriptions-item>
                <a-descriptions-item label="行业分类">{{
                    detail.industry_txt || "--"
                  }}
                </a-descriptions-item>
                <a-descriptions-item label="客商标签">
                  <TagList
                      v-if="detail.tag_info_arr && detail.tag_info_arr.length"
                      :list="detail.tag_info_arr"
                      :type="2"
                  />
                  <span v-else>--</span>
                </a-descriptions-item>
                <a-descriptions-item label="邮箱">{{
                    detail.email || "--"
                  }}
                </a-descriptions-item>
                <a-descriptions-item label="财务客商编码">
                  {{ detail.tenant_no || "--" }}
                </a-descriptions-item>
                <a-descriptions-item label="所属房源">
                  <span :class="isModal ? 'webkit-line3' : ''">
                    {{ getRoomDetail() }}
                  </span>
                </a-descriptions-item>
              </a-descriptions>
            </a-card>
          </a-col>
          <a-col :span="24" v-if="detail.is_personal != 1">
            <a-card title="工商信息" :bordered="false">
              <a-descriptions layout="vertical" :column="4" :colon="false">
                <a-descriptions-item label="统一社会信用代码">
                  {{ businessInfo.unifiedSocialCreditCode || "--" }}
                </a-descriptions-item>
                <a-descriptions-item label="纳税人识别号">
                  {{ businessInfo.taxpayerIdNumber || "--" }}
                </a-descriptions-item>
                <a-descriptions-item label="注册号">
                  {{ businessInfo.registrationNumber || "--" }}
                </a-descriptions-item>
                <a-descriptions-item label="组织机构代码">
                  {{ businessInfo.organizationCode || "--" }}
                </a-descriptions-item>
                <a-descriptions-item label="法定代表人">
                  {{ businessInfo.legalPerson || "--" }}
                </a-descriptions-item>
                <a-descriptions-item label="国籍">
                  {{ businessInfo.birthCountry || "--" }}
                </a-descriptions-item>
                <a-descriptions-item label="注册资本">
                  {{ businessInfo.registeredCapital || "--" }}
                </a-descriptions-item>
                <a-descriptions-item label="存续状态">
                  {{ businessInfo.operatingState || "--" }}
                </a-descriptions-item>
                <a-descriptions-item label="登记机关">
                  {{ businessInfo.registrationAuthority || "--" }}
                </a-descriptions-item>
                <a-descriptions-item label="公司类型">
                  {{ businessInfo.companyType || "--" }}
                </a-descriptions-item>
                <a-descriptions-item label="人员规模">
                  {{ businessInfo.staffSize || "--" }}
                </a-descriptions-item>
                <a-descriptions-item label="英文名">
                  {{ businessInfo.englishName || "--" }}
                </a-descriptions-item>
                <a-descriptions-item label="成立日期">
                  {{ businessInfo.business_info_founding_time || "--" }}
                </a-descriptions-item>
                <a-descriptions-item label="核准日期">
                  {{ businessInfo.approvalTime || "--" }}
                </a-descriptions-item>
                <a-descriptions-item label="营业期限">
                  {{ businessInfo.business_info_business_term || "--" }}
                </a-descriptions-item>
                <a-descriptions-item label="所属地区">
                  {{ businessInfo.district || "--" }}
                </a-descriptions-item>
                <a-descriptions-item label="所属行业" span="2">
                  {{ businessInfo.industry || "--" }}
                </a-descriptions-item>
                <a-descriptions-item label="注册地址" span="3">
                  {{ businessInfo.address || "--" }}
                </a-descriptions-item>
                <a-descriptions-item label="经营范围" span="3">
                  {{ businessInfo.businessScope || "--" }}
                </a-descriptions-item>
              </a-descriptions>
            </a-card>
          </a-col>
          <a-col :span="24" v-if="detail.is_personal != 1">
            <a-card title="账户信息" :bordered="false">
              <a-descriptions layout="vertical" :column="4" :colon="false">
                <a-descriptions-item label="开户银行">
                  {{ invoiceInfo.bank || "--" }}
                </a-descriptions-item>
                <a-descriptions-item label="账号">
                  {{ invoiceInfo.account || "--" }}
                </a-descriptions-item>
                <a-descriptions-item label="电话">
                  {{ invoiceInfo.tel || "--" }}
                </a-descriptions-item>
                <a-descriptions-item label="纳税人识别号">
                  {{ invoiceInfo.taxpayerIdNumber || "--" }}
                </a-descriptions-item>
                <a-descriptions-item label="默认发票类型">
                  {{ invoiceInfo.invoice_type_txt || "--" }}
                </a-descriptions-item>
                <a-descriptions-item label="开票地址">
                  {{ invoiceInfo.address || "--" }}
                </a-descriptions-item>
                <a-descriptions-item label="默认发票模板">
                  {{ invoiceInfo.template_name || "--" }}
                </a-descriptions-item>
              </a-descriptions>
            </a-card>
          </a-col>
        </a-row>
      </div>
      <owner-contract-table
          v-if="activeTabKey == 'contract'"
          :id="id"
          @closeAllModal="closeAllModal"
      />
      <owner-bill-table v-if="activeTabKey == 'bill'" :id="id"/>
      <a-table
          :dataSource="dataSource"
          :columns="columns"
          :pagination="false"
          :loading="loading"
          rowKey="id"
          v-if="activeTabKey == 'file'"
      >
        <template #bodyCell="{ text, record, index, column }">
          <template v-if="column.key === 'name'">
            <a-input
                v-if="record.editable"
                v-model:value="record.name"
                style="width: 150px"
            />
            <span v-else>{{ record.name }}</span>
          </template>
          <template v-if="column.key === 'action'">
            <span v-if="record.editable">
              <a-button type="link" @click="saveClick(record)"> 确认</a-button>
              <a-button type="link" @click="clearClick(record)"
              >取消</a-button
              ></span
            >
            <span v-else>
              <a-button
                  type="link"
                  :disabled="
                  !record.online_preview.previewUrl &&
                  record.online_preview.documentType !== 'pic'
                "
                  @click="previewClick(record)"
              >
                <EyeOutlined/>
              </a-button>
              <a-button type="link" @click="editClick(record)"
              ><EditOutlined
              /></a-button>
              <a-button type="link" @click="downLoadClick(record.url)"
              ><DownloadOutlined
              /></a-button>
              <a-button danger type="link" @click="deleteClick(record.id)"
              ><DeleteOutlined
              /></a-button>
            </span>
          </template>
        </template>

        <template #title>
          <a-row type="flex" justify="space-between" style="padding: 0 20px">
            <a-col>附件信息</a-col>
            <a-col
            >
              <a-button @click="enclosureClick"
              >
                <PlusOutlined/>
                添加附件
              </a-button
              >
            </a-col
            >
          </a-row>
        </template>
      </a-table>
      <a-table
          v-if="activeTabKey == 'invoice'"
          :dataSource="dataSourceInvoice"
          :columns="columnsInvoice"
          :loading="loadingInvoice"
          :pagination="invoicePagination"
          @change="handleTableChangeInvoice"
          rowKey="id"
          sticky
          :scroll="{ x: 1500 }"
      >
        <template #headerCell="{ column }">
          <template v-if="column.key === 'company_type'">
            纳税人资质
            <a-tooltip>
              <template #title>
                <div>非一般纳税人</div>
                <div>不支持开专票</div>
              </template>
              <question-circle-outlined/>
            </a-tooltip>
          </template>
        </template>
        <template #bodyCell="{ column, record, text }">
          <template v-if="column.key == 'company_type'">
            {{ text == 0 ? "一般纳税人" : text == 1 ? "非一般纳税人" : "--" }}
          </template>
          <template v-if="column.key == 'title_type'">
            {{ text == 0 ? "个人" : text == 1 ? "企业" : "--" }}
          </template>
          <template v-if="column.key == 'action'">
            <a-space>
              <a-button type="link" @click="bankAccountClick(record)"
              >银行账号
              </a-button
              >
              <a-button type="link" @click="editInvoice(record)">编辑</a-button>
              <a-tooltip>
                <template #title v-if="record.is_system"
                >默认数据，无法删除
                </template
                >
                <a-button
                    type="text"
                    danger
                    @click="deleteInvoice(record.id)"
                    :disabled="record.is_system ? true : false"
                >删除
                </a-button
                >
              </a-tooltip>
            </a-space>
          </template>
          <template
              v-if="
              column.key !== 'company_type' &&
              column.key !== 'action' &&
              column.key !== 'title_type'
            "
          >
            {{ text || "--" }}
          </template>
        </template>
        <template #title>
          <a-row justify="space-between" style="padding: 0 20px">
            <a-col>开票信息</a-col>
            <a-col
            >
              <a-button @click="invoiceClick">
                <PlusOutlined/>
                添加
              </a-button>
            </a-col>
          </a-row>
        </template>
      </a-table>
      <a-table
          v-if="activeTabKey == 'customer'"
          :columns="customerColumns"
          :data-source="customerList"
          rowKey="id"
          sticky
          :scroll="{ x: 1500 }"
          :pagination="customPagination"
          @change="handleTableChange"
      >
        <template #title>
          <div class="flex justify-between header-clue">
            <div class="flex-1">
              <a-form layout="vertical">
                <a-row :gutter="8" :wrap="true" type="flex">
                  <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                    <a-form-item>
                      <a-input
                          placeHolder="搜索联系人名称"
                          v-model:value="searchParams.name"
                      />
                    </a-form-item>
                  </a-col>
                  <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                    <a-form-item>
                      <a-input
                          placeHolder="搜索联系人电话"
                          v-model:value="searchParams.tel"
                      />
                    </a-form-item>
                  </a-col>
                  <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                    <a-form-item>
                      <a-input
                          placeHolder="搜索公司名称"
                          v-model:value="searchParams.companyName"
                      />
                    </a-form-item>
                  </a-col>
                  <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                    <a-form-item>
                      <a-select
                          style="width: 100%"
                          :allowClear="true"
                          placeholder="请选择意向项目"
                          v-model:value="searchParams.village_id"
                          :options="villageList"
                      />
                    </a-form-item>
                  </a-col>
                  <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                    <a-form-item>
                      <a-select
                          style="width: 100%"
                          placeholder="请选择客户状态"
                          :allowClear="true"
                          v-model:value="searchParams.status"
                          :options="customerStatusOptions"
                      >
                      </a-select>
                    </a-form-item>
                  </a-col>

                  <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                    <a-form-item>
                      <a-select
                          style="width: 100%"
                          placeholder="请选择客户渠道"
                          :allowClear="true"
                          v-model:value="searchParams.channel_id"
                          :options="customerChannelOptions"
                      >
                      </a-select>
                    </a-form-item>
                  </a-col>

                  <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                    <a-form-item>
                      <a-range-picker
                          class="w-100p"
                          v-model:value="searchParams.created_time"
                          :value-format="dateFormatStr"
                          @change="handleRangePickerChange"
                      />
                    </a-form-item>
                  </a-col>

                  <a-col>
                    <a-form-item label="">
                      <a-space>
                        <a-button @click="reset">重置</a-button>
                        <a-button type="primary" @click="searchCustomList">
                          搜索
                        </a-button>
                      </a-space>
                    </a-form-item>
                  </a-col>


                </a-row>
              </a-form>
            </div>
          </div>
        </template>

        <template #bodyCell="{ column, record, text }">
          <template v-if="column.key == 'company'">
            {{ record.customer?.company || '--' }}
          </template>
          <template v-if="column.key == 'name'">
            {{ record.customer?.name }}-{{ record.customer?.tel }}
          </template>
          <template v-if="column.key == 'channel_name'">
            <template v-if="record.channel_name">
              <a-button type="link" @click="checkChannel(record.customer.channel_id)">{{
                  record.channel_name
                }}
              </a-button>
            </template>
            <template v-else>--</template>
          </template>
          <template v-if="column.key=='status_txt'">
            <span class="text-green" v-if="record.status_txt=='成交'">已成交</span>
            <span class="text-blue" v-else>{{ record.status_txt }}</span>
          </template>

          <template v-if="column.key=='budget_amount'">
            <span>{{ record.customer?.budget_amount }}元</span>
          </template>
          <template v-if="column.key == 'expect_area'">
            {{ record.customer?.expect_area_min }}-{{ record.customer?.expect_area_max }}m²
          </template>

          <template v-if="column.key === 'tag_arr'">
            <tempalte v-if="text?.length">
              <a-tag v-for="(item, index) in text" :key="index">{{ item.name }}</a-tag>
            </tempalte>
            <tempalte v-else>
              <span>--</span>
            </tempalte>
          </template>
          <template v-if="column.key == 'action'">
            <a-space>

              <a-button type="link" @click="checkBindCustomer(record.customer_id)">详情</a-button>
              <a-tooltip>
                <template #title v-if="record.not_removable"
                >该意向客户已成交，不可解除
                </template
                >
                <a-button
                    type="text"
                    danger
                    @click="cancelBindCustomer(record.id)"
                    :style="{'color':record.not_removable?'#999':'red'}"
                    :disabled="record.not_removable ? true : false"
                >解除绑定
                </a-button
                >
              </a-tooltip>
            </a-space>
          </template>

        </template>

      </a-table>
    </section>
    <OwnerContEdit
        :visible="editModalVisible"
        @cancel="handleEditModalClose"
        @updateList="handleEditModalUpdate"
        :id="id"
        @btnok="handleEditModalConfirm"
    />
    <!--添加附件 -->
    <Files
        :visible="enclosureVisible"
        @success="successClick"
        @onCancel="() => (enclosureVisible = false)"
        :id="id"
    />

    <!-- 合同预览 -->
    <ElectronContractModal
        :visible="electronContractVisible"
        :urlData="previewUrlData"
        :esignDetail="{
        esignCheck: true,
      }"
        type="owner"
        title="在线预览"
        @close="electronContractVisible = false"
    />

    <!-- 预览图片 -->
    <PreviewImg
        :visible="imgVisible"
        :index="0"
        :list="imgList"
        @close="imgVisible = false"
    />

    <!-- 添加开票信息 -->
    <AddInvoice
        :visible="invoiceVisible"
        :id="invoiceId"
        :ownerId="ownerId"
        @successChange="successChange"
        @closeChange="invoiceVisible = false"
        :detail="detail"
    />

    <!-- 银行账户 -->
    <BankAccount
        :visible="bankAccountVisible"
        :id="invoiceId"
        :ownerId="ownerId"
        @closeChange="getInvoiceList()"
    />

    <!--  客户详情  -->
    <CustomerDetail
        :visible="detailVisible"
        :id="detailId"
        @handleCancel="detailVisible=false"
    />

    <!-- 详情 -->
    <ChannelInfoDetail
        :id="channelId"
        :visible="channelVisible"
        @cancel="channelVisible = false"
        @closeDetail="infoVisible=false"
    />
  </div>
</template>

<script>
import {
  defineComponent,
  ref,
  createVNode,
  onActivated,
  watch,
  computed,
  reactive,
  toRefs
} from "vue";
import {useRoute, useRouter} from "vue-router";
import request from "../../../common/utils/request";
import OwnerContEdit from "./modules/OwnerContEdit.vue";
import {Modal, message, Form} from "ant-design-vue";
import {
  ExclamationCircleOutlined,
  DeleteOutlined,
  EditOutlined,
  PlusOutlined,
  DownloadOutlined,
  ArrowLeftOutlined,
  EyeOutlined,
  QuestionCircleOutlined, FormOutlined,
} from "@ant-design/icons-vue";
import TagList from "../../../components/Tag/show.vue";
import OwnerContractTable from "./OwnerContractTable.vue";
import OwnerBillTable from "./OwnerBillTable.vue";
import Files from "./modules/Files.vue";
import _ from "lodash";
import {PreviewImg} from "bl-common-vue3";

import ElectronContractModal from "../../../components/ElectronContractModal/index.vue";

import AddInvoice from "./modules/AddInvoice.vue";
import BankAccount from "./modules/BankAccount.vue";
import store from '@/store'
import CustomerDetail from '@/views/village/BusinessManage/modules/CustomerDetail.vue'
import ChannelInfoDetail from '@/views/village/BusinessManage/modules/ChannelInfoDetail.vue'

const useForm = Form.useForm;
const dateFormatStr = "YYYY-MM-DD";

export default defineComponent({
  name: "ownerDetail",
  props: {
    // 展示方式 modal page
    showType: {
      type: String,
      default: "page",
    },
    // showType=modal 必传
    id: {
      type: [Number, String],
      default: 0,
    },
  },
  components: {
    FormOutlined,
    ChannelInfoDetail,
    CustomerDetail,
    OwnerContEdit,
    TagList,
    OwnerContractTable,
    OwnerBillTable,
    DownloadOutlined,
    ArrowLeftOutlined,

    DeleteOutlined,
    EditOutlined,
    PlusOutlined,
    Files,

    EyeOutlined,
    ElectronContractModal,
    PreviewImg,
    AddInvoice,
    QuestionCircleOutlined,

    BankAccount,
  },
  setup(props, {emit}) {
    const $router = useRouter();
    const $route = useRoute();

    const isModal = computed(() => props.showType == "modal");

    const tabList = ref({});
    const activeTabKey = ref("detail");
    const editModalVisible = ref(false);
    const detail = ref({});
    const businessInfo = ref({});
    const invoiceInfo = ref({});
    const id = ref(Number($route.query.id));
    const notBack = $route.query.noBack;

    const tab_org = {
      detail: {title: "详情"},
      contract: {title: "合同"},
      bill: {title: "账单"},
      file: {title: "附件"},
      invoice: {title: "开票信息"},
    };

    const goBack = (close = true) => {
      if (isModal.value) {
        if (close) {
          emit("cancel");
        }
      } else {
        if (window.history.state.back) {
          $router.back();
        } else {
          $router.replace({
            name: "ownerList",
          });
        }
      }
    };

    const closeAllModal = () => {
      emit("closeAllModal");
    };

    const OwnerEdit = () => {
      editModalVisible.value = true;
    };

    const OwnerDelete = () => {
      Modal.confirm({
        title: "确认删除该租客吗？",
        icon: createVNode(ExclamationCircleOutlined),
        okText: "确认",
        cancelText: "取消",
        onOk() {
          request.del("/org", "/owner/manage", {id: id.value}).then((res) => {
            message.success("删除成功");
            goBack();
          });
        },
      });
    };

    // 关闭编辑弹窗
    const handleEditModalClose = () => {
      editModalVisible.value = false;
    };

    //保存编辑弹窗
    const handleEditModalUpdate = () => {
      handleEditModalClose();
    };

    //保存编辑弹窗
    const handleEditModalConfirm = () => {
      getOwnerDetail();
      handleEditModalClose();
    };

    const getRoomDetail = () => {
      if (
          !detail.value.build_bind ||
          !detail.value.build_bind.room ||
          !detail.value.build_bind.room.length
      ) {
        return "--";
      }
      const {room} = detail.value.build_bind;
      const showTxtArr = room.map(
          (item) =>
              `${detail.value.build_bind.village.name}/${item.extra.build_name}/${item.layer_name}/${item.room_name}`
      );
      return showTxtArr.join("、");
    };

    // 获取订单详情
    const ownerId = ref(0);

    const getOwnerDetail = () => {
      request
          .get("/org", "/owner/info", {
            id: id.value,
          })
          .then((res) => {
            businessInfo.value = {};
            invoiceInfo.value = {};
            console.log(res);
            detail.value = res.detail;
            ownerId.value = res.detail.id;
            if (res.detail.business_info) {
              businessInfo.value = res.detail.business_info;
            }
            if (res.detail.invoice_info) {
              invoiceInfo.value = res.detail.invoice_info;
            }
            if (res.detail.is_bind_customer) {
              tab_org.customer = {title: "意向客户列表"}
              tabList.value = tab_org
              getStatus()
              getChannelList()
              getVillageList()
            }
          });
    };


    const state = reactive({
      customLoading: false,
      customerList: [],
      detailVisible: false,
      detailId: 0,
      customerStatusOptions: [],
      customerChannelOptions: [],
      villageList: [],
      channelVisible: false,
      channelId: 0,

    })


    const searchParams = reactive({
      name: "", // 联系人名称
      tel: "", // 联系人电话
      companyName: '', // 公司名称
      village_id: undefined, // 意向项目id
      status: undefined, // 客户状态
      channel_id: undefined, // 客户渠道id
      created_time: undefined,
      start_time: undefined,
      end_time: undefined,
    });
    const {resetFields} = useForm(searchParams, {});

    const customPage = ref(1)
    const customPageSize = ref(10)
    const customTotal = ref(0)
    const customPagination = computed(() => ({
      total: customTotal.value,
      current: customPage.value,
      pageSize: customPageSize.value,
      showSizeChanger: true,
    }))

    const getStatus = () => {
      request.get("/org", "/business/customer/statusList", {}).then((res) => {
        state.customerStatusOptions = res.list.map((item) => ({
          value: item.status,
          label: item.name,
          ...item,
        }));
      });
    };

    const getChannelList = () => {
      request
          .get("/org", "/business/customer/channel/index", {})
          .then((res) => {
            state.customerChannelOptions = res.list.map((item) => {
              return {
                value: item.id,
                label: item.name,
              };
            });
          });
    };

    const getVillageList = () => {
      request
          .get("/org", "/build/villageAndBuildList/v2", {
            checked: 1,
          })
          .then((res) => {
            let vList = [];
            res.villageList.forEach((item) => {
              vList.push({
                label: item.name,
                value: item.id,
              });
            });
            state.villageList = vList;
          });
    };
    const getCustomerList = () => {
      state.customLoading = true
      const params = {
        owner_id: ownerId.value,
        page: customPage.value,
        pageSize: customPageSize.value
      }

      if (searchParams.created_time) {
        searchParams.start_time = searchParams.created_time[0];
        searchParams.end_time = searchParams.created_time[1];
      }
      for (let key in searchParams) {
        if (searchParams[key] || searchParams[key] === 0) {
          params[key] = searchParams[key];
        }
      }
      delete params.created_time;
      request.post("/org", "/business/customer/bindCustomerList", params).then(res => {
        state.customLoading = false
        state.customerList = res.list
        customTotal.value = res.total
        console.log(res)
      })
      console.log(tabList.value)
    }

    const reset = () => {
      resetFields();
      searchCustomList()
    };

    const searchCustomList = () => {
      customPage.value = 1
      getCustomerList()
    }


    const handleTableChange = (pager) => {
      customPage.value = pager.current;
      customPageSize.value = pager.pageSize;
      getCustomerList();
    };


    const handleRangePickerChange = (date, dateString) => {
      searchParams.created_time = date;
    };
    const customerColumns = [
      {
        title: "公司名称",
        align: "center",
        dataIndex: "company",
        key: "company",
        fixed: store.getters.isMobile ? undefined : "left",
        width: 150,
      },

      {
        title: "联系人",
        align: "center",
        dataIndex: "name",
        key: "name",
        width: 150,
      },
      {
        title: "客户状态",
        align: "center",
        dataIndex: "status_txt",
        key: "status_txt",
        width: 150,
      },
      {
        title: "关联渠道",
        align: "center",
        dataIndex: "channel_name",
        key: "channel_name",
        width: 150,
      },
      {
        title: "客户预算",
        align: "center",
        dataIndex: "budget_amount",
        key: "budget_amount",
        width: 150,
      },
      {
        title: "意向项目",
        align: "center",
        dataIndex: "village_name",
        key: "village_name",
        width: 150,
      },
      {
        title: "需求面积段",
        align: "center",
        dataIndex: "expect_area",
        key: "expect_area",
        width: 150,
      },

      {
        title: "签约时间",
        align: "center",
        dataIndex: "expect_contract_time",
        key: "expect_contract_time",
        customRender: ({text}) => {
          return text || '--';
        },
        width: 180,
      },
      {
        title: "标签",
        align: "center",
        dataIndex: "tag_arr",
        key: "tag_arr",
        width: 180,
      },
      {
        title: "操作",
        align: "center",
        dataIndex: "id",
        key: "action",
        width: 180,
        fixed: "right",
      },
    ]
    // 附件
    const columns = [
      {
        title: "文件名",
        dataIndex: "name",
        key: "name",
        width: 300,
      },
      {
        title: "上传人",
        dataIndex: "user_name",
        key: "user_name",
      },
      {
        title: "上传时间",
        dataIndex: "updated_at",
        key: "updated_at",
      },
      {
        title: "操作",
        dataIndex: "id",
        key: "action",
        width: 300,
      },
    ];
    const dataSource = ref([]);
    const loading = ref(false);

    const filesList = () => {
      loading.value = true;
      request
          .get("/org", "/owner/files/list", {owner_id: id.value})
          .then((res) => {
            dataSource.value = res.list;
            loading.value = false;
          });
    };
    // 添加附件
    const enclosureVisible = ref(false);
    const enclosureClick = () => {
      enclosureVisible.value = true;
    };

    const successClick = () => {
      enclosureVisible.value = false;
      filesList();
    };
    const deleteClick = (id) => {
      Modal.confirm({
        title: `确认删除该数据吗?`,
        icon: createVNode(ExclamationCircleOutlined),
        okText: "确认",
        cancelText: "取消",
        onOk() {
          request.del("/org", "/owner/files", {id}).then((res) => {
            message.success("删除成功");
            filesList();
          });
        },
      });
    };

    const editClick = (record) => {
      dataSource.value.forEach((item) => {
        if (item.id == record.id) {
          item.editable = true;
        } else {
          item.editable = false;
        }
      });
    };
    // 下载
    const iframe = document.createElement("iframe");
    const downLoadClick = (url) => {
      // iframe.src = url;
      // iframe.style.display = "none";
      // document.body.appendChild(iframe);
      // setTimeout(() => {
      //   document.body.removeChild(iframe);
      // }, 1000);
      window.open(url);
    };

    const saveClick = ({name, id}) => {
      dataSource.value.forEach((item) => {
        if (item.id == id) {
          item.editable = false;
        }
      });
      request.put("/org", "/owner/files", {name, id}).then((res) => {
        message.success("修改成功");
        filesList();
      });
    };
    const clearClick = ({id}) => {
      dataSource.value.forEach((item) => {
        if (item.id == id) {
          item.editable = false;
        }
      });
    };

    // 合同预览 && 图片预览
    const electronContractVisible = ref(false);
    const previewUrlData = ref({});

    const imgVisible = ref(false);
    const imgList = ref([]);

    const previewClick = (record) => {
      if (record.online_preview) {
        if (record.online_preview.documentType == "pic") {
          imgList.value = [record.url];
          imgVisible.value = true;
          return;
        }
        if (record.online_preview.documentType == "word") {
          previewUrlData.value = {
            previewUrl: record.online_preview.previewUrl,
            url: record.url,
          };
          electronContractVisible.value = true;
        }
      }
    };

    // 开票信息
    const dataSourceInvoice = ref([]);
    const columnsInvoice = ref([
      {
        title: "发票抬头",
        dataIndex: "title",
        key: "title",
      },
      {
        title: "抬头类型",
        dataIndex: "title_type",
        key: "title_type",
      },
      {
        title: "银行账户数量",
        dataIndex: "account_num",
        key: "account_num",
      },
      {
        title: "纳税人识别号",
        dataIndex: "tax_number",
        key: "tax_number",
      },
      {
        title: "企业注册地址",
        dataIndex: "tax_company_address",
        key: "tax_company_address",
      },
      {
        title: "企业注册电话",
        dataIndex: "tax_company_tel",
        key: "tax_company_tel",
      },
      {
        title: "纳税人资质",
        dataIndex: "company_type",
        key: "company_type",
      },
      {
        title: "添加时间",
        dataIndex: "created_at",
        key: "created_at",
      },
      {
        title: "操作",
        dataIndex: "action",
        key: "action",
        fixed: "right",
        width: 220,
      },
    ]);
    const loadingInvoice = ref(false);
    const invoiceId = ref(0);
    const invoiceVisible = ref(false);
    const totalInvoice = ref(0);
    const invoicePage = ref(1);
    const invoicePageSzie = ref(20);
    const invoiceClick = () => {
      invoiceId.value = 0;
      invoiceVisible.value = true;
    };
    const successChange = () => {
      invoiceVisible.value = false;
      getInvoiceList();
    };

    const invoicePagination = computed(() => ({
      total: totalInvoice.value,
      current: invoicePage.value,
      pageSize: invoicePageSzie.value,
      showSizeChanger: true,
    }));
    const handleTableChangeInvoice = (pager, filters, sorter) => {
      invoicePage.value = pager.current;
      invoicePageSzie.value = pager.pageSize;
      getInvoiceList();
    };

    const getInvoiceList = () => {
      bankAccountVisible.value = false;
      let params = {
        owner_id: Number($route.query.id) || detail.value.id,
        page: invoicePage.value,
        pageSize: invoicePageSzie.value,
      };
      loadingInvoice.value = true;
      request
          .get("/org", "/org/owner/invoice/title", params)
          .then((res) => {
            dataSourceInvoice.value = res.list;
            totalInvoice.value = res.total;
            loadingInvoice.value = false;
          })
          .catch(() => {
            loadingInvoice.value = false;
          });
    };

    // 开票银行账户
    const bankAccountVisible = ref(false);
    const bankAccountClick = (record) => {
      invoiceId.value = record.id;
      bankAccountVisible.value = true;
    };

    // 开票编辑
    const editInvoice = (record) => {
      invoiceId.value = record.id;
      invoiceVisible.value = true;
    };

    // 删除开票信息
    const deleteInvoice = (id) => {
      Modal.confirm({
        title: "确认删除该条开票信息吗？",
        icon: createVNode(ExclamationCircleOutlined),
        okText: "确认",
        cancelText: "取消",
        onOk() {
          request.del("/org", `/org/owner/invoice/title/${id}`).then((res) => {
            message.success("删除成功");
            getInvoiceList();
          });
        },
      });
    };

    const checkBindCustomer = (id) => {
      state.detailId = id
      state.detailVisible = true
    }

    const cancelBindCustomer = (id) => {
      Modal.confirm({
        title: "确认解绑该条客户信息吗？",
        icon: createVNode(ExclamationCircleOutlined),
        okText: "确认",
        cancelText: "取消",
        onOk() {
          request.del("/org", `/business/customer/relieveBind`, {id: id}).then((res) => {
            message.success("解绑成功");
            customPage.value = 1
            getCustomerList();
          });
        },
      });
    }

    const checkChannel = (val) => {
      state.channelId = val;
      state.channelVisible = true
    }

    watch(
        () => activeTabKey.value,
        (val) => {
          if (val == "file") {
            filesList();
          }
          if (val == "invoice") {
            getInvoiceList();
          }
          if (val == "customer") {
            getCustomerList();
          }
        }
    );

    const init = () => {
      tabList.value = tab_org;
      if (isModal.value) {
        id.value = props.id;
        getOwnerDetail();
      }
    };
    init();

    onActivated(() => {
      id.value = Number($route.query.id);
      getOwnerDetail();
    });

    return {
      tabList,
      activeTabKey,
      editModalVisible,
      detail,
      businessInfo,
      invoiceInfo,
      id,
      OwnerEdit,
      OwnerDelete,
      handleEditModalClose,
      handleEditModalUpdate,
      handleEditModalConfirm,
      closeAllModal,
      // 附件
      columns,
      dataSource,
      deleteClick,
      enclosureClick,
      enclosureVisible,
      successClick,
      loading,
      editClick,
      clearClick,
      saveClick,
      downLoadClick,
      getRoomDetail,

      isModal,
      goBack,
      previewClick,
      electronContractVisible,
      previewUrlData,
      imgList,
      imgVisible,

      columnsInvoice,
      dataSourceInvoice,
      loadingInvoice,

      invoiceClick,
      invoiceVisible,
      invoiceId,
      successChange,

      invoicePagination,
      handleTableChangeInvoice,
      deleteInvoice,
      editInvoice,
      bankAccountClick,
      bankAccountVisible,
      getInvoiceList,

      ownerId,
      notBack,

      getCustomerList,
      customerColumns,
      ...toRefs(state),
      cancelBindCustomer,
      customPagination,
      checkBindCustomer,
      searchParams,
      dateFormatStr,
      handleRangePickerChange,
      reset,
      searchCustomList,
      handleTableChange,
      checkChannel,


    };
  },

  beforeRouteEnter(to, from, next) {
    next((e) => {
      if (from.fullPath == "/apps/orgVillage/ownerList") {
        e.activeTabKey = "detail";
      }
    });
  },
});
</script>

<style lang="less" scoped>
.owner-detail {
  height: 100%;

  .header {
    background-color: #ffffff;

    :deep(.tag-list .tag) {
      margin-right: 10px;
    }

    :deep(.ant-tabs-bar) {
      margin-bottom: 0;
      border-bottom: none;
    }

    :deep(.ant-tabs-ink-bar) {
      height: 3px;
    }
  }

  .content {
    position: relative;
    z-index: 90;
    flex: 1;
    width: 100%;
    max-height: calc(100% - 100px);
    padding: 20px 10px;
    box-sizing: border-box;
    overflow-y: auto;
  }
}

.webkit-line3 {
  word-break: break-all;
  text-overflow: ellipsis;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  display: -webkit-box;
  overflow: hidden;
}

:deep(.ant-table-sticky-holder) {
  top: -20px !important;
}

:deep(.ant-descriptions-item-label) {
  margin-bottom: -8px;
}

.hide-back {
  :deep(.ant-page-header-back) {
    display: none;
  }
}
</style>
